package tl_model

import (
	"log"

	"gorm.io/gorm"
)

// JobInfo 定义表结构
type JobInfo struct {
	gorm.Model

	ID       uint   `gorm:"primaryKey"`              // 主键
	JobName  string `gorm:"type:varchar(255);index"` // 职位名称
	JobCount int64  `gorm:"not null"`                // 职位数量
}

func (*JobInfo) TableName() string {
	return "jobinfo"
}

// save or update
func (j *JobInfo) Save() error {
	// 根据 j.JobName 保存任务， 如果不存在则创建，存在则更新
	result := GetDB().Where(JobInfo{JobName: j.JobName}).Assign(JobInfo{
		JobCount: j.JobCount,
	}).FirstOrCreate(&j, JobInfo{JobName: j.JobName})
	if result.Error != nil {
		return result.Error
	}
	return nil
}

// get job by job_name
func GetJobInfo(jobName string) (*JobInfo, error) {
	db := GetDB()
	var job JobInfo
	result := db.Where("job_name = ?", jobName).First(&job)
	if result.Error != nil {
		log.Panicf("Failed to get job: %v", result.Error)
	}
	return &job, nil
}
